package com.tkc.redis.impl;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.tkc.common.util.JsonUtil;
import com.tkc.redis.UserDataService;
import com.tkc.redis.model.doo.UserData;

/**
 * redis 的insert/delete/update/select 操作入口
 * @author tankaichao
 *
 */
@Service
public class UserDataServiceImpl implements UserDataService {
    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> valueOperations;
    @Resource(name = "redisTemplate")
    private RedisTemplate<String, String>   redisTemplate;

    @Override
    public boolean insertUserData(String key, UserData userData) {
        try {
            return valueOperations.setIfAbsent(key,
                JsonUtil.DB_EXTENSION_INSTANCE.writeValueAsString(userData));
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean deleteUserData(String key) {
        try {
            redisTemplate.delete(key);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean updateUserData(String key, UserData userData) {
        try {
            valueOperations.set(key, JsonUtil.DB_EXTENSION_INSTANCE.writeValueAsString(userData));
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    @Override
    public UserData selectUserData(String key) {
        try {
            return JsonUtil.DB_EXTENSION_INSTANCE.readValue(valueOperations.get(key),
                UserData.class);
        } catch (Exception e) {
            return null;
        }
    }

}
